package home

import (
	"adai.design/homeserver/members"
	"encoding/json"
	"errors"
	"fmt"
)

const (
	MemberStateUnknown =  0
	MemberStateArrive  =  1
	MemberStateLeave   =  2

	MemberRuleAdmin = "admin"
	MemberRuleGuest = "guest"
)

type Member struct {
	Id 		string		`json:"id" bson:"id"`
	Role 	string		`json:"role" bson:"role"`
	State 	int			`json:"-" bson:"-"`
}

type MemberManager struct {
	members []*Member
}

func (ms *MemberManager) getMember(id string) *Member {
	for _, m := range ms.members {
		if m.Id == id {
			return m
		}
	}
	return nil
}

func (ms *MemberManager) setState(id string, state int) (*Member, error) {
	for _, m := range ms.members {
		if m.Id == id {
			if m.State != state {
				m.State = state
				return m, nil
			}

			return m, errors.New("unchanged state")
		}
	}
	return nil, fmt.Errorf("membership(%s) 404 not found", id)
}

type MemberDesc struct {
	Id 		string		`json:"id"`
	Role 	string		`json:"role"`
	Name 	string		`json:"name"`
	Icon 	string		`json:"icon"`
	State 	int			`json:"state"`
}

// 成员的查找、添加、删除
func (ms *MemberManager) Handle(h *Home, pkg *members.MessagePkg) error {
	msg := pkg.Msg

	if msg.Method == members.MsgMethodGet {
		var infos []*MemberDesc
		for _, m := range ms.members {
			if membership := members.GetMembership(m.Id); membership != nil {
				desc := &MemberDesc{
					Id: membership.Id,
					Role: m.Role,
					Name: membership.Name,
					Icon: membership.Icon,
					State: m.State,
				}
				infos = append(infos, desc)
			}
		}
		buf, _ := json.Marshal(infos)
		ack := &members.MessagePkg{
			Type: pkg.Type,
			Ctx: pkg.Ctx,
			Msg: &members.Message{
				Path: msg.Path,
				Method: msg.Method,
				State: "ok",
				Home: h.Id,
				Data: buf,
			},
		}
		h.replyMemberResult(ack)
	}
	return nil
}

// 主要功能
// 获取头像、名字
// 更新位置
// 推送消息